<?php

//echo $mtDate = date('Y-m-d');
//exit;
require_once ("libs/Authorize/AuthorizeNet.php"); 
require_once ("libs/NMI/nmi.php"); 
require_once("libs/Mijireh/Mijireh.php");
require_once("paypal/paypal.class.php");
require_once("libs/swift/swift_required.php");

@session_start();

class Checkout extends Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {

        $paymentArray = $_SESSION['paymentArray'];
        $sql = new sql();
        $sql->connect();
        $serverreply = "";

        if (count($_SESSION['shoping_cart']) == 0) {
            header("Location: " . URL . "product");
        }
        
       
        
        //check if final amount is less than zero then redirect to cart page
        $total_Amount_chk = 0;
        $Discount_price_chk = 0;
        foreach ($_SESSION['shoping_cart'] as $key => $value) {
            $total_Amount_chk += $value['prd_qty'] * $value['prd_price'];
        }
        $cat_match_qty = 1;
        if (isset($_SESSION['coupon_detail'])) {
            $Discount_price_chk = $_SESSION['coupon_detail']['coupon_price'];
            $Discount_code = $_SESSION['coupon_detail']['coupon_code'];
            $coupon_category = $_SESSION['coupon_detail']['coupon_category'];
            $coupon_product = $_SESSION['coupon_detail']['coupon_product'];
            $coupon_type = $_SESSION['coupon_detail']['coupon_type'];
            $coupon_applied = $_SESSION['coupon_detail']['coupon_applied'];
            if ($coupon_type == 'collection' && $coupon_applied == 'per_item') {
                $cat_match_qty = 0;
            }
            if ($coupon_type == 'specific_product' && $coupon_applied == 'per_item') {
                $cat_match_qty = 0;
            }
            $total_Amount = '';
            foreach ($_SESSION['shoping_cart'] as $key => $value) {
                $total_Amount = $total_Amount + ($value['prd_qty'] * $value['prd_price']);

                if ($coupon_type == 'collection' && $coupon_applied == 'per_item') {
                    if ($value['prd_cat_id'] == $coupon_category) {
                        $cat_match_qty += $value['prd_qty'];
                    }
                }
                if ($coupon_type == 'specific_product' && $coupon_applied == 'per_item') {
                    if ($value['prd_id'] == $coupon_product) {
                        $cat_match_qty += $value['prd_qty'];
                    }
                }
            }
        }




        $Final_amount_with_discount = $total_Amount_chk - ($Discount_price_chk * $cat_match_qty);
        if ($Final_amount_with_discount <= 0) {
            header("Location: " . URL . "cart");
        }

        if ($Final_amount_with_discount <= 0 && (isset($_SESSION['coupon_detail']) && $_SESSION['coupon_detail']['coupon_staus'] == 'invalid')) {
            header("Location: " . URL . "cart");
        }



        $errorArray = Array();
        //$this->view->ErrorMessage = '';

        $salutation = '';
        $fname = '';
        $lname = '';
        $email = '';
        $zipcode = '';
        $address = '';
        $state = '';
        $city = '';
        $phone = '';
        $country = '';
        $ag_name = '';
        $terms = '';
        $drpgateway = '';
        $payment_option = '';
        $drpCardType = '';
        $txtCreditcardno = '';
        $drpExpMonth = '';
        $expyear = '';
        $nameoncard = '';
        $cvv = '';
		$Discount_code = '';
            
            
        if (@$_POST['submit']) {

            
            function ValidEmailAddress($EmailAddress) {
                if (!preg_match("/^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i", $EmailAddress)) {
                    return false;
                }
                return true;
            }
            
            function isNumeric($n) {
                if (!preg_match("/^[0-9]+$/", $n)) {
                    return false;
                }
                return true;
            }

            $salutation = $_POST['salutation'];
            $fname = $_POST['fname'];
            $lname = $_POST['lname'];
            $email = $_POST['email'];
            $zipcode = $_POST['zipcode'];
            $address = $_POST['address'];
            $state = $_POST['state'];
            $city = $_POST['city'];
            $ag_name = $_POST['ag_name'];
            $phone = $_POST['phone'];
            $country = $_POST['country'];
            $agent_id = trim($_POST['ag_name']);
            
            $drpgateway = $_POST['drpgateway'];
            if($_POST['drpgateway'] != 'Paypal'){
                $payment_option = $_POST['payment_optn'];
                $drpCardType = $_POST['drpCardType'];
                $txtCreditcardno = $_POST['txtCreditcardno'];
                $drpExpMonth = $_POST['drpExpMonth'];
                $expyear = $_POST['expyear'];
                $nameoncard = $_POST['nameoncard'];
                $cvv = $_POST['cvv'];
            }
            
            
            
            if (array_key_exists('terms', $_POST)) {
                $terms = $_POST['terms'];
            }

            if (trim($_POST['salutation']) == "") {
                $errorArray[] = 'Please select salutation';
            }

            if (trim($_POST['fname']) == "") {
                $errorArray[] = 'Please enter firstname';
            }

            if (trim($_POST['lname']) == "") {
                $errorArray[] = 'Please enter lastname';
            }

            if (trim($_POST['email']) == "") {
                $errorArray[] = 'Please enter email';
            }

            if (!ValidEmailAddress($_POST['email'])) {
                $errorArray[] = 'Please enter valid email';
            }

            if (trim($_POST['zipcode']) == "") {
                $errorArray[] = 'Please enter zipcode';
            }

            if (trim($_POST['address']) == "") {
                $errorArray[] = 'Please enter address';
            }

            if (trim($_POST['state']) == "") {
                $errorArray[] = 'Please enter state';
            }

            if (trim($_POST['city']) == "") {
                $errorArray[] = 'Please enter city';
            }

            if (trim($_POST['phone']) == "") {
                $errorArray[] = 'Please enter phone no.';
            }

            if (trim($_POST['country']) == "") {
                $errorArray[] = 'Please select country';
            }
            if (trim($terms) == "") {
                $errorArray[] = 'Please select terms and conditions';
            }

            if (trim($_POST['drpgateway']) == "credit_card") {
               
                if (trim($payment_option) == "") {
                    $errorArray[] = 'Please select payment method';
                }
                if (trim($drpCardType) == "") {
                    $errorArray[] = 'Please select card type';
                }
                if (trim($payment_option) == "") {
                    $errorArray[] = 'Please select payment method';
                }
                if (trim($txtCreditcardno) == "") {
                    $errorArray[] = 'Please enter credit number';
                }
                if (trim($txtCreditcardno) != "" && !isNumeric($txtCreditcardno)) {
                    $errorArray[] = 'Please enter valid credit number';
                }
                if (trim($drpExpMonth) == "") {
                    $errorArray[] = 'Please select month';
                }
                if (trim($expyear) == "") {
                    $errorArray[] = 'Please select year';
                }
                if (trim($nameoncard) == "") {
                    $errorArray[] = 'Please enter name on card';
                }
                if (trim($cvv) == "") {
                    $errorArray[] = 'Please enter cvv number';
                }
                
            }



            if (count($errorArray) > 0) {
                
            } else {
                $total_Amount = 0;
                $Discount_price = 0;
                $cat_match_count = 1;
                $cat_match_qty = 1;
                $coupon_applied = '';
                $coupon_product = '';
                $coupon_category = '';
                if (isset($_SESSION['coupon_detail'])) {
                    $Discount_price = $_SESSION['coupon_detail']['coupon_price'];
                    $Discount_code = $_SESSION['coupon_detail']['coupon_code'];
                    if ($_SESSION['coupon_detail']['coupon_applied'] == 'per_item') {
                        $cat_match_count = 0;
                        $cat_match_qty = 0;
                        $coupon_applied = 'per_item';
                        $coupon_category = $_SESSION['coupon_detail']['coupon_category'];
                        $coupon_product = $_SESSION['coupon_detail']['coupon_product'];
                    }
                }

                foreach ($_SESSION['shoping_cart'] as $key => $value) {
                    $total_Amount += $value['prd_qty'] * $value['prd_price'];
                    if (($value['prd_cat_id'] == $coupon_category) && $coupon_applied == 'per_item') {
                        $cat_match_count +=1;
                        $cat_match_qty += $value['prd_qty'];
                    }
                    if (($value['prd_id'] == $coupon_product) && ($coupon_applied == 'per_item')) {
                        $cat_match_count +=1;
                        $cat_match_qty += $value['prd_qty'];
                    }
                }





                $Final_amount_with_discount = $total_Amount - ($Discount_price * $cat_match_qty);


                $UserArray = $sql->fetch("tbl_user", array("user_email" => $_POST['email']));
                if ($UserArray['user_id'] != '') {
                    // echo 'in';exit;
                    $lastid = $UserArray['user_id'];
                } else {
                    $arraydata = array("user_prefix" => $_POST['salutation'],
                        "user_firstname" => $_POST['fname'],
                        "user_lastname" => $_POST['lname'],
                        "user_email" => $_POST['email'],
                        "user_zipcode" => $_POST['zipcode'],
                        "user_address" => $_POST['address'],
                        "user_state" => $_POST['state'],
                        "user_city" => $_POST['city'],
                        "user_phoneno" => $_POST['phone'],
                        "user_country" => $_POST['country'],
                        "user_createdate" => date('Y-m-d h:i:s'),
                        "user_status" => 1,
                        "user_terms" => $_POST['terms']
                    );
                    $insert = $sql->insert('tbl_user', $arraydata);
                    $lastid = $sql->last_id();


                    include('quickbooks/add_customer.php');
                    //$last_quickbook_id = $resp;
                }
                //add product in quickbook 
                include('quickbooks/addproduct.php');



                //Mijireh Store 1
                $mij_access_key = "";
                $pt_type = "";

                //$mir_array = array();
                foreach ($paymentArray as $p_key => $p_value) {
                    if ($_POST['payment_optn'] == $p_key) {
                        $mij_access_key = $p_value['mij_access_key'];
                        $pt_type = $p_value['Name'];
                    }
                }


                
              
                //get customer id from db
                $UserArray = $sql->fetch("tbl_user", array("user_id" => $lastid));
                $payment_type = '';
                $last_quickbook_id = $UserArray['quick_book_id'];
                $user_firstname = $UserArray['user_firstname'];
                $user_email = $UserArray['user_email'];


                //Paypal
                if (@$_POST['drpgateway'] == 'Paypal') {
                    $CANCEL_URL = URL . "checkout?dn_id=1";
                    $RETURN_URL = URL . "thankyou/" . $lastid . "/paypal/" . trim($_POST['payment_optn']) . "/" . trim($_POST['ag_name']);

                    $paypalPaymentArray = Array();
                    $paypalPaymentArray['dn_firstname'] = $fname;
                    $paypalPaymentArray['dn_lastname'] = $lname;
                    $paypalPaymentArray['dn_address'] = $address;
                    $paypalPaymentArray['dn_city'] = $city;
                    $paypalPaymentArray['dn_state'] = $state;
                    $paypalPaymentArray['dn_country'] = $country;
                    $paypalPaymentArray['dn_zipcode'] = $zipcode;
                    $paypalPaymentArray['dn_email'] = $email;
                    $paypalPaymentArray['dn_phone'] = $phone;


                    $paypalmode = (PAYPAL_MODE == 'sandbox') ? '.sandbox' : '';

                    $total_Amount_pay = 0;
                    $ItemName = '';
                    $ItemPrice = '';
                    $ItemDesc = '';
                    $ItemQty = '';
                    $ItemTotalPrice = '';
                    $i = 1;
                    $parmsString = '';
                    $j = 0;
                    foreach ($_SESSION['shoping_cart'] as $s_key => $s_value) {
                        $total_Amount_pay += $s_value['prd_qty'] * $s_value['prd_price'];
                        $ItemName = $s_value['prd_name'];
                        $ItemPrice = $s_value['prd_price'];
                        $ItemDesc = $s_value['prd_desc'];
                        $ItemQty = $s_value['prd_qty'];
                        $ItemTotalPrice = $ItemPrice * $ItemQty;
                        $parmsString .= '&L_PAYMENTREQUEST_0_NAME' . $j . '=' . urlencode($ItemName) .
                                //'&L_PAYMENTREQUEST_0_DESC'.$j.'=' . urlencode($ItemDesc) .
                                '&L_PAYMENTREQUEST_0_AMT' . $j . '=' . urlencode($ItemPrice) .
                                '&L_PAYMENTREQUEST_0_QTY' . $j . '=' . urlencode($ItemQty);
                        $j++;
                        $i++;
                    }






                    $discountString = '';
                    $no_discount_code = $j;
                    $discountTotalPrice = 0;


                    if (isset($_SESSION['coupon_detail'])) {
                        $discountName = "Discount Code - " . $_SESSION['coupon_detail']['coupon_code'];
                        $discountPrice = "-" . $_SESSION['coupon_detail']['coupon_price']; //Item Price
                        $discountDescription = $_SESSION['coupon_detail']['coupon_code'];
                        $discountQty = $cat_match_qty; // Item Quantity
                        $discountTotalPrice = $discountPrice * $discountQty;
                        $discountString = '&L_PAYMENTREQUEST_0_NAME' . $no_discount_code . '=' . urlencode($discountName) .
                                //'&L_PAYMENTREQUEST_0_DESC'.$no_discount_code.'=' . urlencode($discountDescription) .
                                '&L_PAYMENTREQUEST_0_AMT' . $no_discount_code . '=' . urlencode($discountPrice) .
                                '&L_PAYMENTREQUEST_0_QTY' . $no_discount_code . '=' . urlencode($discountQty);
                    }
                    $GrandTotal = $total_Amount_pay + $discountTotalPrice;

                    //Parameters for SetExpressCheckout, which will be sent to PayPal
                    $padata = '&METHOD=SetExpressCheckout' .
                            '&RETURNURL=' . urlencode($RETURN_URL) .
                            '&CANCELURL=' . urlencode($CANCEL_URL) .
                            '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") .
                            $parmsString .
                            //Discount 
                            $discountString .
                            '&SOLUTIONTYPE=Sole' .
                            '&LANDINGPAGE=Billing' .
                            '&PAYMENTREQUEST_0_SHIPTONAME=' . $paypalPaymentArray['dn_firstname'] . " " . $paypalPaymentArray['dn_lastname'] .
                            '&PAYMENTREQUEST_0_SHIPTOSTREET=' . $paypalPaymentArray['dn_address'] .
                            '&PAYMENTREQUEST_0_SHIPTOCITY=' . $paypalPaymentArray['dn_city'] .
                            '&PAYMENTREQUEST_0_SHIPTOSTATE=' . $paypalPaymentArray['dn_state'] .
                            '&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=' . $paypalPaymentArray['dn_country'] .
                            '&PAYMENTREQUEST_0_SHIPTOZIP=' . $paypalPaymentArray['dn_zipcode'] .
                            '&EMAIL=' . $paypalPaymentArray['dn_email'] .
                            '&PAYMENTREQUEST_0_SHIPTOPHONENUM=' . $paypalPaymentArray['dn_phone'] .
                            '&NOSHIPPING=1' .
                            '&PAYMENTREQUEST_0_AMT=' . urlencode($GrandTotal) .
                            '&ALLOWNOTE=1';

                    //We need to execute the "SetExpressCheckOut" method to obtain paypal token
                    $paypal = new MyPayPal();
                    $httpParsedResponseAr = $paypal->PPHttpPost('SetExpressCheckout', $padata, PAYPAL_API_USERNAME, PAYPAL_API_PASSWORD, PAYPAL_API_SIGNATURE, PAYPAL_MODE);
                    
                    
                    //Respond according to message we receive from Paypal
                    if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {

                        //Redirect user to PayPal store with Token received.
                        $paypalurl = 'https://www' . $paypalmode . '.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=' . $httpParsedResponseAr["TOKEN"] . '';
                        header('Location: ' . $paypalurl);
                    } else {
                        //Show error message
                       header("Location: " . URL . "payment_error/".$user_id);
                     //   echo '<div style="color:red"><b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
                    }
                }
                if (@$_POST['drpgateway'] == 'credit_card') {
                    if($payment_option == 'authorize'){
                        $sale = new AuthorizeNetAIM; 
                        $sale->amount = $Final_amount_with_discount; 
                        $sale->card_num = $txtCreditcardno; 
                        $sale->exp_date = $drpExpMonth."/".$expyear;
                        $sale->first_name = $fname; 
                        $sale->last_name = $lname; 
                        $sale->email = $email;
                        $sale->address = $address;
                        $sale->state = $state;
                        $sale->city = $city;
                        $sale->phone = $phone;
                        $sale->country = $country;
                        $sale->zip = $zipcode;
                        $response = $sale->authorizeAndCapture();
                       
                        if ($response->approved) { 
                            $orderNum = $response->transaction_id;
                            $transaction_id = "Authorize - " . $orderNum;
                           //$transaction_id = $response->transaction_id; 
                            $paymentdata = array(
                                "pt_type" => 'credit_visa',
                                "pt_store" => 'authorize',
                                "pt_user_id" => $lastid,
                                "pt_coupon_code" => $Discount_code,
                                "pt_coupon_price" => $Discount_price,
                                "pt_coupon_qty" => $cat_match_qty,
                                "pt_amt_without_cp" => $total_Amount,
                                "pt_transaction_id" => $response->transaction_id,
                                "pt_agent_id" => $agent_id,
                                "pt_total_amount" => $Final_amount_with_discount,
                                "pt_createDate" => date('Y-m-d h:i:s'),
                                "pt_status" => 'active',
                            );

                            $sql->insert('payment_order', $paymentdata);
                            $lastpaymentid = $sql->last_id();


                            $responsedata = array(
                                "pr_pt_id" => $lastpaymentid,
                                "pr_response" => serialize($response),
                                "pr_createdate" => date('Y-m-d h:i:s'),
                                "pr_status" => 'active',
                            );
                            $sql->insert('tbl_payment_response', $responsedata);
                            foreach ($_SESSION['shoping_cart'] as $key => $value) {
                            $orderdata = array("or_user_id" => $lastid,
                                "or_product_id" => $value['prd_id'],
                                "payment_ref_id" => $lastpaymentid,
                                "or_prd_qty" => $value['prd_qty'],
                                "or_prd_price" => $value['prd_price'],
                                "or_price" => $value['prd_qty'] * $value['prd_price'],
                                "or_createdate" => date('Y-m-d h:i:s'),
                                "or_status" => 1,
                            );
                            $insert_order = $sql->insert('tbl_order', $orderdata);
                            $keyArray = $sql->fetch("tbl_metadata", array("mtd_key" => 'payment_key'));
                            $key = $keyArray['mtd_value'];

                            if ($key == count($paymentArray)) {
                                $updatedKey = 1;
                            } else {
                                $updatedKey = $key + 1;
                            }

                            $update = $sql->update('tbl_metadata', array("mtd_value" => $updatedKey), array("mtd_key" => 'payment_key'));
                        }
                            include('quickbooks/salerecepit.php');
                        } else{
                            header("Location: " . URL . "payment_error/".$lastid);
                        }
                    }
                    if($payment_option == 'nmi'){
                        $gw = new gwapi;
                        $username = USERNAME_NMI; 
                        $password = PASSWORD_NMI;
                        $gw->setLogin($username, $password);
                        $orderid = rand(100,1000);
                        
                        $gw->setBilling($fname,$lname,$address, $city, $state, $zipcode,
                        $country,$phone, $email);
                        $gw->setShipping($fname, $lname, $address,$city,
                                $state,$zipcode,$country,$email);
                        $gw->setOrder($orderid);
                        $r = $gw->doSale($Final_amount_with_discount, $txtCreditcardno, $drpExpMonth.$expyear, $cvv);
                        //print $gw->responses['responsetext'];

                        
                        if($gw->responses['responsetext'] == 'SUCCESS'){
                            $orderNum = $gw->responses['transactionid'];
                            $transaction_id = "NMI - " . $orderNum;
                           //$transaction_id = $response->transaction_id; 
                            $paymentdata = array(
                                "pt_type" => 'credit_visa',
                                "pt_store" => 'Nmi',
                                "pt_user_id" => $lastid,
                                "pt_coupon_code" => $Discount_code,
                                "pt_coupon_price" => $Discount_price,
                                "pt_coupon_qty" => $cat_match_qty,
                                "pt_amt_without_cp" => $total_Amount,
                                "pt_transaction_id" => $orderNum,
                                "pt_agent_id" => $agent_id,
                                "pt_total_amount" => $Final_amount_with_discount,
                                "pt_createDate" => date('Y-m-d h:i:s'),
                                "pt_status" => 'active',
                            );

                            $sql->insert('payment_order', $paymentdata);
                            $lastpaymentid = $sql->last_id();


                            $responsedata = array(
                                "pr_pt_id" => $lastpaymentid,
                                "pr_response" => serialize($gw->responses),
                                "pr_createdate" => date('Y-m-d h:i:s'),
                                "pr_status" => 'active',
                            );
                            $sql->insert('tbl_payment_response', $responsedata);
                            foreach ($_SESSION['shoping_cart'] as $key => $value) {
                            $orderdata = array("or_user_id" => $lastid,
                                "or_product_id" => $value['prd_id'],
                                "payment_ref_id" => $lastpaymentid,
                                "or_prd_qty" => $value['prd_qty'],
                                "or_prd_price" => $value['prd_price'],
                                "or_price" => $value['prd_qty'] * $value['prd_price'],
                                "or_createdate" => date('Y-m-d h:i:s'),
                                "or_status" => 1,
                            );
                            $insert_order = $sql->insert('tbl_order', $orderdata);
                            $keyArray = $sql->fetch("tbl_metadata", array("mtd_key" => 'payment_key'));
                            $key = $keyArray['mtd_value'];

                            if ($key == count($paymentArray)) {
                                $updatedKey = 1;
                            } else {
                                $updatedKey = $key + 1;
                            }

                            $update = $sql->update('tbl_metadata', array("mtd_value" => $updatedKey), array("mtd_key" => 'payment_key'));
                        }
                            include('quickbooks/salerecepit.php');
                        }else{
                            header("Location: " . URL . "payment_error/".$lastid);
                        }
                        
                    }
                    if($payment_option == 'first-data'){
                        
                    }
                }
                
                /*if (@$_POST['drpgateway'] == 'Mijireh') {
                    // Mijireh Payment
                    Mijireh::$access_key = $mij_access_key; //244ec644addfa238a4602d58';//<your_mijireh_store_access_key>;
                    // get store info
                    $store_info = Mijireh::get_store_info();
                    $address = new Mijireh_Address();
                    $address->street = $_POST['address'];
                    $address->city = $_POST['city'];
                    $address->state_province = $_POST['state'];
                    $address->zip_code = $_POST['zipcode'];
                    $address->country = $_POST['country'];
                    $address->phone = $_POST['phone'];
                    $address->first_name = $_POST['fname'];
                    $address->last_name = $_POST['lname'];
                    $order = new Mijireh_Order();
                    $order->set_shipping_address($address);
                    $order->set_billing_address($address);
                    $order->add_email_detail($_POST['email']);
                    foreach ($_SESSION['shoping_cart'] as $key => $value) {
                        $price = $value['prd_qty'] * $value['prd_price'];
                        $order->add_item($value['prd_name'], $value['prd_price'], $value['prd_qty'], 'product' . $key);
                    }


                    $order->return_url = URL . "thankyou/" . $lastid . "/mijireh/" . trim($_POST['payment_optn']) . "/" . trim($_POST['ag_name']);
                    //'http://localhost/kanijfatma/payment_gateway/mijireh/thankyou.php';
                    $order->shipping = 0.00;
                    $order->tax = 0.00;
                    $order->discount = $Discount_price * $cat_match_qty;
                    $order->total = $Final_amount_with_discount; //$total_Amount; // sum of items + shipping + tax - discount
                    $order->create();
                    header('Location: ' . $order->checkout_url);
                }
                */
            }
        }


        //Fetch the Current Key
        $keyArray = $sql->fetch("tbl_metadata", array("mtd_key" => 'payment_key'));
        $key = $keyArray['mtd_value'];

        $updatedPaymentArray = array();
        foreach ($paymentArray as $p_key => $p_value) {
            $updatedPaymentArray[$p_key] = $p_value['Name'];
        }




        for ($i = $key + 1; $i <= count($paymentArray); $i++) {
            $paymentstore[$i] = $updatedPaymentArray[$i];
        }

        for ($j = 1; $j <= $key; $j++) {
            $paymentstore[$j] = $updatedPaymentArray[$j];
        }

        /* Agent Array */
        $agentArray = array();
        $agentArray = $sql->fetchAll("tbl_agent", array("ag_status" => 1));

        $this->view->agentArray = $agentArray;
        $this->view->salutation = $salutation;
        $this->view->fname = $fname;
        $this->view->lname = $lname;
        $this->view->email = $email;
        $this->view->zipcode = $zipcode;
        $this->view->address = $address;
        $this->view->state = $state;
        $this->view->city = $city;
        $this->view->phone = $phone;
        $this->view->country = $country;
        $this->view->ag_name = $ag_name;
        $this->view->terms = $terms;
        
        $this->view->drpgateway = $drpgateway;
        $this->view->payment_optn = $payment_option;
        $this->view->drpCardType = $drpCardType;
        $this->view->txtCreditcardno = $txtCreditcardno;
        $this->view->drpExpMonth = $drpExpMonth;
        $this->view->drpExpYear = $expyear;
        $this->view->txtNameoncard = $nameoncard;
        $this->view->txtCvv = $cvv;
        
        $this->view->ErrorMessage = $errorArray;
        $this->view->paymentstore = $paymentstore;
        $this->view->render('checkout');
    }

}

